<template>
  <div class="home">
    <section class="my_header">
      <section @click = "gotoback()" class="my_header_left">
        <i class="icon_style iconfont icon-arrowleft"></i>
        <button class="back">返回</button>
      </section>
      <section class="my_header_center">
        <span>{{$store.state.roomDetail.name}}</span>
      </section>
      <section class="my_header_right">
        <i class="icon_style iconfont icon-category"></i>
      </section>
    </section>



    <input type="file" id="fileinput" multiple="multiple" accept="image/png,image/gif,image/jpeg" ref="fileInput" v-on:change="addImg" style="display:none"/>
    <!--<img src="" alt="" id="img_add" @click="startUploadImg" style="display:none">-->

    <section class="center">

      <ul class="photo_list_ul" v-infinite-scroll="getPhotos"
          infinite-scroll-disabled="loading"
          infinite-scroll-distance="10">
        <li class="photo_list_li" v-for="(item, index) in photoList" :key="item.id" @click="showBigImg(index)">
          <section class="img_show">
            <img :src="$store.state.baseImgUrl+item.photoKey" alt="" class="img_show_item">
          </section>
        </li>
        <li class="photo_list_li">
            <section class="img_upload">
              <i class="icon_style iconfont icon-v_shangchuan1" @click="uploadClick"></i>
          </section>
        </li>
      </ul>
      <p class="load_content" v-show="!startShowLoading && showLoading">
        <spinner class="load_icon" type="snake"></spinner>
      </p>
    </section>



    <jm-footer></jm-footer>

    <transition name="loading">
      <spinner class="load_icon" type="snake" v-show="startShowLoading"></spinner>
    </transition>
    <transition name="router-slid" mode="out-in">
      <router-view></router-view>
    </transition>

    <swipe
      ref="swipe"
      :show="showSwiper"
      :images="photoList"
      @hide="showSwiper = false"
    ></swipe>

  </div>
</template>
<script>
  import {mapState, mapMutations} from 'vuex'
  import JmFooter from '../../components/footer/Footer';
  import { Spinner,Toast } from 'mint-ui'
  import CryptoJS from 'crypto-js'
  import Uploader from '../../service/nos-js-sdk';
  import Swipe from '../../components/common/swipe.vue';


  export default {
    data () {
      return {
        selected:"1",
        photoList:[],
        addPhotoList:[],  //上传图片列表
        result: null,
        preventRepeat: false,
        showLoading: true,
        startShowLoading: true,
        offset: 0,
        loading: false,
        commentBoxVisible:false,
        article: "",
        showSwiper: false,
      }
    },
    mounted () {
    },
    computed: {},
    methods: {
      ...mapMutations([
        'SAVE_ARTICLE'
      ]),
      gotoback(){
        this.$router.go(-1)
      },
      uploadClick(){
        document.getElementById("fileinput").click();
      },
      addImg() {
        let fileinput = document.getElementById('fileinput');
        let i = 0;
        for(; i < fileinput.files.length; i ++){
          let image = fileinput.files[i]
          let reader = new FileReader();
          reader.readAsBinaryString(image);

          reader.onload = function (e) {
            let name = CryptoJS.MD5(e.target.result).toString()+'.jpg';
            this.addPhotoList.push(name);
            this.uploadImg(image, name);
          }.bind(this);
        }

      },

      uploadImg(image, fileName){
        let that = new Uploader();
        let param = {
          bucketName: 'jimikongjian',
          objectName: fileName,
          token: this.getToken(fileName),
          trunkSize: 4 * 1024 * 1024,
        }


        if (image) {
          that.addFile(image, function(curFile){
            console.log(curFile.fileName + ' is added.');
          });
          that.upload(param, function(curFile){
            console.log('File: ' + curFile.fileName + ' is uploaded.');
            console.log(image)
            this.createPhoto(fileName);
//            this.addImgToContent(fileName);
          }.bind(this));

        }

      },

      //获取上传凭证
      getToken(Object){
        let p = {
          "Bucket" : "jimikongjian",
          "Object" : Object,
          "Expires" : this.$store.state.expiresTime
        }
        let putPolicy = JSON.stringify(p);
        let wordArray = CryptoJS.enc.Utf8.parse(putPolicy);
        let encodedPutPolicy = CryptoJS.enc.Base64.stringify(wordArray);
        let sign = CryptoJS.HmacSHA256(encodedPutPolicy, this.$store.state.accessSecret);
        let encodedSign = CryptoJS.enc.Base64.stringify(sign);
        return "UPLOAD " + this.$store.state.accessKey + ":" + encodedSign + ":" + encodedPutPolicy;
      },

      async createPhoto(fileName){
          let photo = {
              "photoKey": fileName,
              "albumId": this.$store.state.albumDetail.id
          }
          let res = "";
          await this.axios.post('/v1/photo', photo)
            .then(response => {
              res = response.data;
            })

        if (res.success){
          let instance = Toast({message: '上传图片成功', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
          this.photoList.push(photo);
        }else{
          let instance = Toast({message: '上传图片出现错误', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
        }
      },
      async getPhotos(){
        this.loading = true;

          let url = "/v1/photo?albumId=" + this.$store.state.albumDetail.id
                  + "&start=" + this.offset
                  + "&length=" + this.$store.state.length
          let res = ""
          await this.axios.get(url)
            .then(response => {
                res = response.data;
            })
          if (res.success){
            this.startShowLoading = false;

         }
          if (res.result.length > 0){
            this.offset += res.result.length;
            let i = 0;
            let img = new Image;
            for (; i < res.result.length; i ++){
                img.src = this.$store.state.baseImgUrl+res.result[i].photoKey;
                res.result[i].width = img.width;
                res.result[i].height = img.height;
            }
            this.photoList = [...this.photoList, ...res.result];
            this.loading = false;
          }

         if (res.result.length < this.$store.state.length) {
            this.showLoading = false;
            return
          }
      },
      showBigImg(index){
        this.showSwiper = true;
        this.$refs.swipe.sildeTo(index, this.photoList);

      }
    },
    components:{
      Swipe,
      Spinner,
      JmFooter
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">

  .mint-toast-text{
    font-size: 0.6rem;
  }
  .toast{
    min-width: 20%;
    width: 20%;
    span{
      color: #FFFFFF;
    }
  }
  .mint-spinner-snake{
    margin: 0 auto;
  }
</style>

<style lang="scss" scoped>
  @import '../../style/mixin';

  .my_header{
    background-color: #33CCFF;
    height: 1.5rem;
    display: flex;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    padding-top: 0.2rem;
    z-index: 100;
    .my_header_left{
      flex: 1;
      margin-left: 0.5rem;

      .icon_style{
        font-size: 0.6rem;
        font-weight: bold;
      }

      .back{
        background-color: transparent;
        font-size: 0.65rem;
        margin: 0;
      }
    }
    .my_header_center{
      flex: 2;
      display: flex;
      text-align: center;
      flex-direction: column;
      align-items: center;
      span{

      }
    }
    .my_header_right{
      flex: 1;
      text-align: right;
      margin-right: 0.5rem;
      .icon_style{
        font-size: 0.65rem;
        font-weight: bold;
        position: relative;
        top: -0.06rem;
      }
    }

  }

  .load_icon{
    display: inline-block;
    height: 100%;
    width: 100%;
    position: relative;
    margin: 0 auto;

  }

  .load_content{
    height: 45px;
    width: 100%;

  }

  .center{
    padding-top: 1.5rem;
    padding-bottom: 2rem;
    overflow: hidden;
  }
  .photo_list_ul{
      margin-top: 0.16rem;
    .photo_list_li{
      display: inline-block;

      .img_show{
        margin: 0  0.16rem;
        .img_show_item{
         @include wh(5rem, 5rem);
        }
      }

      .img_upload{
        @include wh(5rem, 5rem);
        .icon_style{
          display: inline-block;
          font-size: 4rem;
          margin: 0 0;
          padding: 0 0;
          position: relative;
          top: -1rem;
        }
      }

    }
  }


  span,input{
    font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;
  }





</style>

